package com.xuecheng.content.controller;

import com.xuecheng.commons.model.vo.CoursePubVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CoursePub;
import freemarker.template.TemplateException;
import org.springframework.web.bind.annotation.*;
import com.xuecheng.content.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * 课程发布前端控制器
 * </p>
 *
 * @author itheima
 */
@Slf4j
@RestController  // controller + responsebody
public class CoursePubController {

    @Autowired
    private CoursePubService coursePubService;


    /*
        springMVC的一个内置对象：ModelAndView（底层就是转发）
     */

    // 课程预览
    @GetMapping("/coursePub/preview/{courseBaseId}")
    public ModelAndView preview(@PathVariable("courseBaseId") Long courseBaseId) {
        // 调用service查询模型
        Map model = coursePubService.preview(courseBaseId);

        // 创建ModelAndView  参数一：视图（模板）名  参数二：模型
        ModelAndView modelAndView = new ModelAndView("learing_article", model);

        // 返回
        return modelAndView;
    }

    // 保存课程发布
    @PostMapping("/coursePub/publish/{courseBaseId}")
    public ResponseResult saveCoursePub(@PathVariable("courseBaseId") Long courseBaseId) throws IOException, TemplateException {
        return coursePubService.saveCoursePub(courseBaseId);
    }

    // 根据id查询课程发布
    @GetMapping("/coursePub/{id}")
    public ResponseResult findById(@PathVariable("id") Long id){
        // 调用service查询
        CoursePub coursePub = coursePubService.getById(id);
        // 转vo
        CoursePubVo vo = BeanHelper.copyProperties(coursePub, CoursePubVo.class);
        // 返回vo
        return ResponseResult.okResult(vo);
    }

}
